package handler

import (
	"context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"ihome/models"
	"ihome/utils"
	"time"

	"github.com/micro/go-micro/util/log"

	login "ihome/proto/login"
)

type Login struct{}

// Call is a single request handler called via client.Call or the generated client code
func (e *Login) SrvLogin(ctx context.Context, req *login.Request, rsp *login.Response) error {
	logs.Info("登陆 SrvLogin /api/v1.0/sessions")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	/*将数据存入数据库*/
	o := orm.NewOrm()
	var user models.User
	qs := o.QueryTable("user")
	err := qs.Filter("mobile", req.Mobile).One(&user)

	if err != nil {
		logs.Info("查询用户失败")
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	if utils.MD5String(req.Password) != user.Password_hash {
		logs.Info("密码错误")
		rsp.Code = utils.RecodePwderr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}


	/*创建sessionid(唯一随机码)*/
	sessionId := utils.MD5String(req.Mobile + req.Password)
	rsp.SessionId = sessionId

	/*以sessionid为key创建session*/
	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}
	bm.Put(sessionId+"name", user.Mobile, time.Second*3600)
	bm.Put(sessionId+"user_id", user.Id, time.Second*3600)
	bm.Put(sessionId+"mobile", user.Mobile, time.Second*3600)

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *Login) Stream(ctx context.Context, req *login.StreamingRequest, stream login.Login_StreamStream) error {
	log.Logf("Received Login.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&login.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *Login) PingPong(ctx context.Context, stream login.Login_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&login.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
